package com.tecnoagrosoft.zafra.control.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.tecnoagrosoft.zafra.control.activity.R;
import com.tecnoagrosoft.zafra.control.activity.fragment.ActividadesFragment;
import com.tecnoagrosoft.zafra.control.activity.fragment.ClimaFragment;
import com.tecnoagrosoft.zafra.control.activity.fragment.HomeMain;
import com.tecnoagrosoft.zafra.control.activity.fragment.NotificacionFragment;
import com.tecnoagrosoft.zafra.control.activity.fragment.PrecioChicagoFragment;
import com.tecnoagrosoft.zafra.control.activity.fragment.ResumenSeguimientoFragment;
import com.tecnoagrosoft.zafra.control.activity.fragment.SincronizacionFragment;
import com.tecnoagrosoft.zafra.control.db.GenericManager;
import com.tecnoagrosoft.zafra.control.db.GestorDB;
import com.tecnoagrosoft.zafra.control.utils.NameAction;


public class HomeActivity extends ActionBarActivity {

	private String[] opcionesMenu;
	private DrawerLayout drawerLayout;
	private ListView drawerList;
	private ActionBarDrawerToggle drawerToggle;
	private CharSequence tituloSeccion;
	private CharSequence tituloApp;
	private GestorDB gestorDB;
	private GenericManager gM;
	private boolean isNofication=false;
	private Fragment fragmentPrimero=  new HomeMain();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);

		Intent intent = getIntent();
		Bundle extra = intent.getExtras();
		if (extra != null) {
			if (extra.containsKey("logueo")) {
				this.alertDialogSync(this, 2);
			}
			if (extra.containsKey("accion")) {
				//comprueba que la cuenta este al dia
				if (extra.getString("accion").equals("OFF"))
					this.alertDialogVencimiento(this, 2);
			}
		}
		
		try{
             String action =  intent.getAction();    
             if(action != null){
          		NameAction nameT = NameAction.valueOf(intent.getAction().toString()); // surround

      			switch (nameT) {
      			

      			case RESUMEN_SEGUIMIENTO:
      				fragmentPrimero= new ResumenSeguimientoFragment();
      				isNofication=true;
      				break;
      				
      			case PRECIO_CHICAGO:
      				fragmentPrimero= new PrecioChicagoFragment();
      				isNofication=true;
      				break;
      				
      			case CLIMA:
      				fragmentPrimero= new ClimaFragment();
      				isNofication=true;
      				break;	
      				
      			case ACTIVIDADES:
      				fragmentPrimero= new ActividadesFragment();
      				isNofication=true;
      				break;	
      				
      			case NOTIFICACION:
      				fragmentPrimero= new NotificacionFragment();
      				isNofication=true;
      				break;	
      				
      			case SINCRONIZAR:
      				fragmentPrimero= new SincronizacionFragment();
      				isNofication=true;
      				break;	

      			default:
      				break;
      			}
             }
         }catch(Exception e){
             Log.e("Zafra_HOme", "Problem consuming action from intent", e);              
         }
		loadHome();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		getMenuInflater().inflate(R.menu.home, menu);
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		// escucho la respuesta de la actividad
		if (resultCode == Activity.RESULT_OK) {

			loadHome();

		}

	}

	/**
	 * carga el home
	 */
	private void loadHome() {
		// esto es para el menu lateral
		opcionesMenu = new String[] { "Pantalla Principal", "Resumen", "Precio Chicago", "Clima", "Actividades", "Notificaciones", "Sincronizar" };
		drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		drawerList = (ListView) findViewById(R.id.left_drawer);

		drawerList.setAdapter(new ArrayAdapter<String>(getSupportActionBar().getThemedContext(), android.R.layout.simple_list_item_1, opcionesMenu));

		
		// para la primera vez
		if (!isNofication)
			fragmentPrimero = new HomeMain();
		FragmentManager fragmentManager = getSupportFragmentManager();
		fragmentManager.beginTransaction().replace(R.id.content_frame, fragmentPrimero).commit();

		drawerList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

				Fragment fragment = null;
				switch (position) {
				case 0:
					fragment = new HomeMain();
					break;
				case 1:
					fragment = new ResumenSeguimientoFragment();
					break;
				case 2:
					fragment = new PrecioChicagoFragment();
					break;
				case 3:
					fragment = new ClimaFragment();
					break;
				case 4:
					fragment = new ActividadesFragment();
					break;
				case 5:
					fragment = new NotificacionFragment();
					break;
				case 6:
					fragment = new SincronizacionFragment();
					break;
				default:
					fragment = new HomeMain();
					break;
				}

				FragmentManager fragmentManager = getSupportFragmentManager();
				fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

				drawerList.setItemChecked(position, true);
				tituloSeccion = opcionesMenu[position];
				getSupportActionBar().setTitle(tituloSeccion);
				drawerLayout.closeDrawer(drawerList);
			}
		});

		tituloSeccion = getTitle();
		tituloApp = getTitle();

		drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {

			public void onDrawerClosed(View view) {
				getSupportActionBar().setTitle(tituloSeccion);
				ActivityCompat.invalidateOptionsMenu(HomeActivity.this);
			}

			public void onDrawerOpened(View drawerView) {
				getSupportActionBar().setTitle(tituloApp);
				ActivityCompat.invalidateOptionsMenu(HomeActivity.this);
			}
		};

		drawerLayout.setDrawerListener(drawerToggle);

		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().setHomeButtonEnabled(true);

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		if (drawerToggle.onOptionsItemSelected(item)) {
			return true;
		}

	
		switch (item.getItemId()) {
		case R.id.action_manual:
			 String url = "http://www.tecnoagrosoft.com/zafra/public/application/backend/manualmovil";
			 Intent inten = new Intent(Intent.ACTION_VIEW);
			 inten.setData(Uri.parse(url));
			 startActivity(inten);
			break;
		case R.id.action_settings:
			Intent i = new Intent(HomeActivity.this, ConfiguracionesActivity.class);

			startActivity(i);

			break;
		case R.id.action_cerrar_sesion:
			cerrarSesion();
			finish();
			break;
	
		default:
			return super.onOptionsItemSelected(item);
		}

		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		drawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		drawerToggle.onConfigurationChanged(newConfig);
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub

		AlertDialog.Builder builder = new AlertDialog.Builder(HomeActivity.this, 2);

		builder.setMessage(R.string.dialog_message_exit).setTitle(R.string.dialog_title_exit);
		builder.setIcon(getResources().getDrawable(android.R.drawable.ic_dialog_alert));

		// Add the buttons
		builder.setPositiveButton(R.string.acept, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.dismiss();
				finish();
			}
		});
		builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				// User cancelled the dialog
			}
		});
		builder.setCancelable(false);
		AlertDialog dialog = builder.create();
		dialog.show();

	}

	private void alertDialogSync(Context context, int in) {
		// TODO Auto-generated method stub
		CharSequence message = null;

		AlertDialog.Builder builder = new AlertDialog.Builder(context, in);

		builder.setTitle(R.string.men_sinc_titulo_home);
		builder.setInverseBackgroundForced(true);
		builder.setMessage(message);
		builder.setMessage(getString(R.string.men_sinc_bienvenida_home) + "\n\n" + getString(R.string.men_sinc_texto2_home) + "\n\n"
				+ getString(R.string.men_sinc_msgSync_home) + "\n\n" + getString(R.string.men_sinc_agradecimiento_home));
		builder.setNeutralButton(R.string.alert_dialog_comenzar, null);
		builder.setCancelable(false);

		AlertDialog alert = builder.create();
		alert.show();
		TextView textmsg = (TextView) alert.findViewById(android.R.id.message);
		textmsg.setTextSize(16);

	}

	private void alertDialogVencimiento(Context context, int in) {
		// TODO Auto-generated method stub
		CharSequence message = null;

		AlertDialog.Builder builder = new AlertDialog.Builder(context, in);

		builder.setTitle(R.string.title_usuario_deshabilitado);
		builder.setInverseBackgroundForced(true);
		builder.setMessage(message);
		builder.setMessage(getResources().getString(R.string.men_usuario_deshabilitado));
		builder.setPositiveButton(getResources().getString(android.R.string.ok), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int boton) {

				cerrarSesion();
				finish();
			}
		});

		builder.setCancelable(false);

		AlertDialog alert = builder.create();
		alert.show();

	}

	private void cerrarSesion() {
		gestorDB = new GestorDB(HomeActivity.this.getApplicationContext());
		SQLiteDatabase db = gestorDB.getWritableDatabase();
		gM = new GenericManager(db);
		String[] columns = { "_id", "nombre", "usuario", "activo", "pass", "apellido" };
		Cursor cu = gM.getObjectWhere("usuario", columns, "activo = 0");
		if (cu.moveToFirst()) {
			do {
				gM.deleteObject("usuario", cu.getInt(cu.getColumnIndex("_id")));

			} while (cu.moveToNext());
		}

		ContentValues update = new ContentValues();
		update.put("activo", 0);

		cu = gM.getObjectWhere("usuario", columns, "activo = 1");
		if (cu.moveToFirst()) {
			gM.updateObject("usuario", update, cu.getInt(cu.getColumnIndex("_id")));
		}
		gM.close();
		db.close();
		gestorDB.close();
	}

}
